// const fs = require('fs')
// const jwt = require('jsonwebtoken')

import {
  Controller,
  Options,
  Post,
  Get,
  // Required,
} from '../decorator/router'

import {
  addUser,
  verifyLogin,
} from '../service/user'

const payload = {}

@Controller('/user')
export default class User {
  @Post('/register')
  async register (ctx, next) {
    console.log('/register')
    let { email, password } = ctx.request.body
    let result = await addUser(email, password)
    console.log(result)
    const { data } = result
    ctx.session.user = {
      email: data.email,
      role: data.role,
      uid: data.uid
    }

    return (ctx.body = {
      code: 0,
      data: {
        email: data.email,
        uid: data.uid
      }
    })
  }

  @Post('/login')
  async login (ctx, next) {
    console.log('/login')
    const { email, password } = ctx.request.body
    const data = await verifyLogin(email, password)
    const { user, match } = data
    if (match) {
      ctx.session.user = {
        _id: user._id,
        email: user.email,
        role: user.role
      }
      return (ctx.body = {
        code: 0,
        data: {
          email: user.email
        }
      })
    }
    
    return (ctx.body = {
      code: 1,
      msg: '用户名或密码错误'
    })
  }

  @Get('/logout')
  async logout (ctx, next) {
    console.log('/logout')

    delete ctx.session.user
    ctx.redirect('/')

    // return (ctx.body = {
    //   code: 0,
    //   msg: '退出登录成功'
    // })
  }
}